package com.sjtu.bookread.myRecyclerview;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public abstract class MyRecyclerViewAdapter<T> extends RecyclerView.Adapter<MyViewHolder> {
    private Context context;
    private int layoutId;
    private List<T> data;
    private OnItemClickListener onItemClickListener;

    public MyRecyclerViewAdapter(Context _context, int _layoutId, List<T> _data) {
        context = _context;
        layoutId = _layoutId;
        data = _data;
    }

    //使用自定义的ViewHolder 和 绑定 ViewHolder

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        MyViewHolder holder = MyViewHolder.get(context,parent,layoutId);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
        convert(holder, data.get(position)); //重载
        if (onItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClickListener.onClick(holder.getAdapterPosition());
                }
            });
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onItemClickListener.onLongClick(holder.getAdapterPosition());
                    return false;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        if (data == null)
            return 0;
        return data.size();
    }

    public interface OnItemClickListener{
        void onClick(int position);
        void onLongClick(int position);
    }

    public abstract void convert(final MyViewHolder holder, final T t);

    public void setOnItemClickListener(OnItemClickListener onItemClickListener1) {
        this.onItemClickListener = onItemClickListener1;
    }

    public void refresh(List<T> list) {
        this.data = list;
        notifyDataSetChanged();
    }
}
